<template>
	<coreshop-page title="订单评价" mode="left">
		<view class="layout-evaluate-box">
			<view class="item-box" v-for="item, index in state.goodsList" :key="index">
				<view class="item">
					<view class="title">商品信息</view>
					<view class="goods">
						<coreshop-goods-card type="horizontal" imgHeight="130rpx" imgWidth="130rpx" :nameOverflow="2"
							:goodsData="hanldeCombinationGoodsData(item)">
							<template #goodPrice></template>
						</coreshop-goods-card>
					</view>
				</view>
				<view class="item">
					<view class="title">商品评分</view>
					<view class="goods">
						<uv-rate :count="5" size="40rpx" v-model="item.score" activeColor="#D33123"></uv-rate>
					</view>
				</view>
				<view class="item">
					<view class="title">评价内容</view>
					<view class="goods">
						<uv-textarea v-model="item.textarea" :textStyle="{ 'font-size': '24rpx' }"
							placeholder="宝贝满足你的期待吗? 说说你的使用心得"></uv-textarea>
					</view>
				</view>
				<view class="item">
					<view class="title">上传图片 （可上传5张）</view>
					<view class="goods">
						<uv-upload :fileList="item.images" multiple :maxCount="5"
							@afterRead="(files: any) => handleUploadVoucher(files, index)"
							@delete="(files: any) => onDeleteImage(files, index)"></uv-upload>
					</view>
				</view>
			</view>
			
			<coreshop-fixed-bottom-button :radius="100" title="提交评价"
				@onClick="handleSubmit"></coreshop-fixed-bottom-button> 
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive } from "vue";
	import { onLoad } from '@dcloudio/uni-app';
	import { queryOrderDetails, queryUploadImages, submitOrderEvaluate } from '@/core/api';
	import { OrderPayStatusEnum, OrderShipStatusEnum, OrderConfirmStatusEnum } from '@/core/enum';
	import type { Response } from '@/core/models';
	import { handleRouteRedirectTo, handleShowToast } from '@/core/utils';

	interface QueryParams {
		orderId : string;
	}

	const state = reactive<{
		goodsList : Array<any>;
		orderId : string;
	}>({
		goodsList: [],
		orderId: '',
	})

	onLoad((query : QueryParams) => {
		if (query.orderId) {
			state.orderId = query.orderId;
			getOrderDetails();
		} else {
			handleShowToast('获取参数失败', 'error', () => {
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 1500)
			});
		}
	});

	const getOrderDetails = async () => {
		const orderDetails = await queryOrderDetails({ id: state.orderId });
		if (orderDetails.status && orderDetails?.data?.payStatus >= OrderPayStatusEnum.yes && orderDetails?.data?.shipStatus >= OrderShipStatusEnum.yes && orderDetails?.data?.confirmStatus >= OrderConfirmStatusEnum.confirmReceipt && !orderDetails?.data?.isComment) {
			state.goodsList = orderDetails?.data?.items?.map((item : any) => {
				item["images"] = [];
				item["textarea"] = "";
				item["upload"] = true;
				item["score"] = 5;
				return item;
			});
		} else {
			handleShowToast('订单不存在或状态不可评价');
		}
	}

	/** 组合商品数据传入组件 */
	const hanldeCombinationGoodsData = (item : any) => {
		return {
			id: item.id,
			image: item.imageUrl,
			name: item.name,
			brief: item.addon,
		}
	}

	/** 上传图片 */
	const handleUploadVoucher = async (files : any, index : number) => {
		if (!files?.file) {
			return;
		}
		let imgArr = [];
		const imgPromises = files.file.map(async (item : any) => {
			return new Promise(async (resolve) => {
				const img : Response<any> = await queryUploadImages(item.url);
				if (img.status) {
					imgArr.push(img?.data?.src)
					resolve(img?.data?.src);
				} else {
					handleShowToast('上传失败');
				}
			})
		});
		await Promise.all(imgPromises);
		state.goodsList[index].images.push(...imgArr.map((url : string) => {
			return {
				url,
			}
		}))
	}

	/** 图片删除 */
	const onDeleteImage = (event : any, index : number) => {
		state.goodsList[index].images.splice(event.index, 1);
	}

	/** 提交评价 */
	const handleSubmit = async () => {
		let items = [];
		state.goodsList.forEach((item : any) => {
			items.push({
				images: item?.images?.map((cell : any) => cell.url) || [],
				orderItemId: item.id,
				score: item.score,
				textarea: item.textarea,
			})
		})
		const orderEvaluate = await submitOrderEvaluate({
			orderId: state.orderId,
			items: items
		});
		if (orderEvaluate.status) {
			handleShowToast('订单评价成功', 'success', () => {
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 2000)
			});
		}
	}
</script>
<style lang="scss" scoped>
	@import './evaluate.scss';
</style>